//
//  NetWorkHandle.m
//  UI20_网络数据请求作业
//
//  Created by dllo on 16/4/6.
//  Copyright © 2016年 付冬梅. All rights reserved.
//

#import "NetWorkHandle.h"

@interface NetWorkHandle ()<NSURLSessionDelegate, NSURLSessionDataDelegate>

@property (nonatomic, strong) NSMutableData *mData;

@end
@implementation NetWorkHandle

+ (void)netWorkHandleWithUrlString:(NSString *)url netWorkDelegate:(id<NetWorkHandleDelegate>)delegate {
    NetWorkHandle *handle = [[NetWorkHandle alloc] init];
    handle.netWorkHandleDelegate = delegate;
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:handle delegateQueue:[NSOperationQueue mainQueue]];
    
    NSURLSessionTask *task = [session dataTaskWithURL:[NSURL URLWithString:url]];
    
    handle.mData = [NSMutableData data];
    
    [task resume];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [self.mData appendData:data];
    
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    
    id result = [NSJSONSerialization JSONObjectWithData:self.mData options:NSJSONReadingMutableContainers error:nil];
    
    if ([self.netWorkHandleDelegate respondsToSelector:@selector(finishNetWorkHandleWithData:)]) {
        [self.netWorkHandleDelegate finishNetWorkHandleWithData:result];
    }
}

@end
